package com.pat.java.tools;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.chinatricom.util.Encrypt;

public class SendSmsThread extends Thread {
	public static SendSmsThread inst;
	
	private static final Logger actlog = Logger.getLogger("ACT");
	private static final Logger log = Logger.getLogger(SendSmsThread.class);
	
	private LinkedBlockingQueue<Message> operaQueue = new LinkedBlockingQueue<Message>();

	public static void init() throws Exception {
		if (inst == null) {
			inst = new SendSmsThread();
		}
	}

	public SendSmsThread() {
	}
	class Message{
		String phone;
		String content;
		
		public String getPhone() {
			return phone;
		}
		public void setPhone(String phone) {
			this.phone = phone;
		}
		public String getContent() {
			return content;
		}
		public void setContent(String content) {
			this.content = content;
		}
	}
	
    
	public void addSendSMSPlayer(Message msg){
		operaQueue.add(msg);
		
		if(operaQueue.size()>500){
			log.warn("send sms queue warning! size = "+operaQueue.size());
		}
	}

	public void exec(Message msg) throws Exception {
		long start = System.currentTimeMillis();
		
		String result = sendSms(msg.getPhone(), msg.getContent());
		
		actlog.info("send_sms|"+msg.getPhone()+"|"+result);
		log.warn("send sms end use time:" + (System.currentTimeMillis() - start));
	}

	public void run() {
		while (true) {
			try {
				Message msg = operaQueue.poll(500, TimeUnit.MILLISECONDS);
				while (msg != null) {
					exec(msg);
					msg = operaQueue.poll();
				}
			} catch (Exception e) {
				log.error("send sms thread error:"+e.getMessage(), e);
			}
		}
	}
	
	private String sendSms(String phone, String content){
		String url = "http://ems.smsway.com.cn/sendSMS.action";
		HttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);
		HttpPost post = new HttpPost(url);
		try {
			List<NameValuePair> params=new ArrayList<NameValuePair>();
		    params.add(new BasicNameValuePair("enterpriseID","13580"));	//企业ID
		    params.add(new BasicNameValuePair("loginName","admin"));	//登录名
		    params.add(new BasicNameValuePair("password",Encrypt.MD5Encode("wtmk#x1152")));		//登录密码
		    params.add(new BasicNameValuePair("smsId",""));				//消息id
		    params.add(new BasicNameValuePair("subPort",""));			//扩展端口
		    params.add(new BasicNameValuePair("mobiles",phone));		//接收手机号码
		    params.add(new BasicNameValuePair("content",content));		//短信内容
		    params.add(new BasicNameValuePair("sendTime",""));			//定时发送时间
		    
		    post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
		    
			HttpResponse response = httpclient.execute(post);
			HttpEntity entity = response.getEntity();
			InputStream inputStream = entity.getContent();

			SAXReader reader = new SAXReader();
			Document document = reader.read(inputStream);
			if(document != null)
			{
				Element root = document.getRootElement();
				Element smsIDElement = root.element("SmsId");
				if(smsIDElement != null)
				{
					return smsIDElement.getText();
				}
			}
			return "0";
		}
		catch (Exception e) 
		{
			log.error("send sms failed:" + e.getMessage(), e);
			return "error";
		}
		finally
		{
			post.abort();
			httpclient.getConnectionManager().closeExpiredConnections();
		}
	}
	
	public static void main(String[] args) {
		SendSmsThread test = new SendSmsThread();
		
		System.out.println(test.sendSms("18689499406", "hello body~!This msg come from Pat Liu for say Hello!"));
	}
}